<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { NEmpty, NIcon, NCard, NButton, NFlex, NAlert, NInput, NTag, NText } from 'naive-ui';
import { LOG_WX, LOG_WX_BIND } from "../service/apis/apis";
import SvgIcon from '../components/SvgIcon.vue';
import { type LocationQueryValue } from 'vue-router';
import { useCounterStore } from './../stores/counter'
import { encrypt, getJmg } from '../service/jmg';
import unifiedLogin from '@/service/login';
const counterStore = useCounterStore()
const router = useRouter()
const route = useRoute()
const doingLogin = ref(false)
const loginUnbind = ref(false)
const errorMessage = ref('')
const successMessage = ref('')
const secret = ref('')
const jmg = ref()

/**
 * 扫码成功、验证成功：直接完成登录
 * 扫码成功、验证失败：当前界面提示用户绑定
 * 扫码失败：提示失败信息，延时跳转登录页面
 * 
 * 非法进入：提示错误信息，延时跳转登录页面
 * 
 * 绑定成功：提示成功信息，延时跳转登录页面
 */
onMounted(() => {
    console.log('进入微信扫码界面', route.query)
    if (counterStore.isLogin) {
        console.log('重复进入')
        return
    }
    getJmg((reslut: any) => {
        if (!reslut.error) {
            secret.value = reslut.secret
            jmg.value = reslut.jmg
        } else {
            // 没有加密狗，绑定环节无法绑定
            return
        }
    })
    const { code, state } = route.query
    if (code && state) {
        console.log('扫码成功', code, state);
        setTimeout(() => {
            wxlogin(code)
        }, 500);
    } else {
        // 非法进入
        delayReturnToMainPage()
    }
})

const wxlogin = (code: string | LocationQueryValue[]) => {
    doingLogin.value = true
    unifiedLogin(router, { code, jmg: jmg.value  }, LOG_WX, {
        resp_get_cb: (res: any) => { doingLogin.value = false; },
        resp_succ_cb: (res: any) => { },
        resp_accept_cb: (res: any) => {
            // 没有加密狗，绑定环节无法绑定
            if (!jmg.value) {
                errorMessage.value = '获取加密狗信息失败，无法进行新用户绑定'
                delayReturnToMainPage()
                return
            }
            loginUnbind.value = true;
        },
        resp_fail_cb: (res: any) => {
            errorMessage.value = res.message;
            delayReturnToMainPage()
        },
        force_login_cancel_cb: (res: any) => {
            router.push('login')
        },
        err_cb: (err: any) => {
            doingLogin.value = false
            errorMessage.value = err.message
            delayReturnToMainPage()
        },

    })
}

const username = ref('')
const password = ref('')
const wxBind = () => {
    const params = {
        code: route.query.code,
        username: username.value,
        encryptedPassword: encrypt(password.value, secret.value),
    }
    LOG_WX_BIND({ params: JSON.stringify(params) }).then((res: any) => {
        loginUnbind.value = false
        console.log('登录返回结果', res);
        if (res.stacode == 200) {
            successMessage.value = '绑定成功，稍后跳转到登录页面'
            delayReturnToMainPage()
        } else {
            errorMessage.value = '绑定失败，该账号已绑定或密码错误'
            setTimeout(() => {
                loginUnbind.value = true
            }, 3000)

        }
    }).catch((err) => {
        loginUnbind.value = false
        errorMessage.value = err.message
        delayReturnToMainPage()
    });
}

const delayReturnToMainPage = () => {
    setTimeout(() => {
        router.push('login')
    }, 3000)
}
</script>

<template>
    <NFlex justify="space-between" style=" border: 0px solid #ff1111; width: 100vw;height: 100vh;">
        <n-flex style="border: 0px solid #ff1111;">
            <div></div>
        </n-flex>
        <n-flex vertical justify="center" style="border: 0px solid #ff1111;">
            <n-card style="width: calc(100vw / 4);height: calc(100vh / 2);">
                <div>
                    <n-empty v-if="doingLogin" description="正在进入AI数字化智慧平台..." style="margin-top: 150px;">
                        <template #icon>
                            <n-icon>
                                <SvgIcon iconClass="zhinengAI"></SvgIcon>
                            </n-icon>
                        </template>
                    </n-empty>
                    <div v-else-if="loginUnbind" style="text-align: center; margin-top: 50px;">
                        <n-tag size="large" type="success">
                            <SvgIcon iconClass="duicuodui10" />
                            <span> 微信已验证 </span>
                        </n-tag>
                        <div style="margin-top: 30px;">
                            <n-text type="success">绑定您的系统账号，下次就能直接扫码登录了</n-text>
                        </div>
                        <div style="margin-top: 30px;">
                            <n-input placeholder="工号/手机号" style="margin-bottom: 10px;" type="text" maxlength="11"
                                show-count clearable v-model:value="username" />
                            <n-input placeholder="密码" type="password" maxlength="16" show-count
                                style="margin-bottom: 10px;" clearable v-model:value="password" />
                        </div>
                        <n-button @click="router.push('login')" style="margin-top: 20px; margin-right: 20px">返回</n-button>
                        <n-button type="primary" @click="wxBind" style="margin-top: 20px;">绑定</n-button>
                    </div>
                    <div v-else style="text-align: center; margin-top: 150px;">
                        <n-alert v-if="successMessage !== ''" title="成功" type="success" style="margin: 30px; ">{{
                            successMessage }}</n-alert>
                        <n-alert v-else-if="errorMessage !== ''" title="失败" type="warning" style="margin: 30px; ">{{
                            errorMessage
                            }}</n-alert>
                    </div>
                </div>
            </n-card>
        </n-flex>
        <n-flex style="border: 0px solid #eee;">
            <div> </div>
        </n-flex>
    </NFlex>
</template>
